<template name="shareview">
	<view>
		<view class="cu-modal" :class="modalName=='posterModal'?'show':''">
			<view class="cu-dialog w80">
				<view class="text-white flex-end margin-bottom">
					点击右上角进行分享
					<image :src="CLOUDPATH+'/gsc/sharejt.png'" mode="aspectFit" class="sharejiao"></image>
				</view>

				<view class="bg-white _poster" v-if="loading" id="_poster" ref="poster">
					<view class=" bg-white main">
						<view v-if="member" class="member space-between align-center margin-lr margin-top">
							<view class="thumb round margin-right-sm">
								<image v-if="member.head_portrait2" :src="member.head_portrait2" mode="aspectFill"></image>
								<image v-else src="https://gsconline-1251028293.cos.ap-guangzhou.myqcloud.com/images/2020/05/19/image_158987220710257979.png"
								 mode="aspectFill"></image>
							</view>
							<view class="name w100 text-left">
								{{member.nickname?member.nickname:member.realname}}
								<view class="text-gray">分享给你一个商品</view>
							</view>
						</view>
						<view class="margin-lr margin-top" v-if="value">
							<view class="goodsimage margin-top">
								<image :src="value.picture2" mode="widthFix" id="goodsimage"></image>
							</view>
						</view>
						<view class="margin text-left">
							<view class="">
								<view class="margin-top-sm text-black text-lg">{{value?value.name:''}}</view>
								<view class="goodsprice text-red text-xsl margin-top-sm margin-bottom text-price">{{value?value.price:''}}</view>
							</view>
							<view class="text-center">
								<image :src="qr_code" mode="aspectFill" class="qrcode"></image>
							</view>
						</view>
					</view>
				</view>

				<!-- #ifdef MP-WEIXIN -->
				<canvas class="canvas" v-if="loading" canvas-id="mycanvas" :style="'height:' + mainHeight+'px;width:' + mainWidth + 'px;'"></canvas>
				<!-- #endif -->
				<image v-if="!loading && previewFile" class="main-img" :src="previewFile" mode="aspectFill" :style="'height:' + mainHeight+'px'"></image>

				<view class="cu-btn cuIcon-roundclose text-white lg margin-top" @tap="modalName=''"></view>

				<view class="text-white">长按保存图片进行分享</view>
			</view>
		</view>

		<view class="cu-modal drawer-modal" :class="modalName=='wechatModal'?'show':''" @tap="modalName=''">
			<view class="cu-dialog w100">
				<view class="text-white text-xxl margin-top-xxl padding-top-xl">
					<view class="margin-top">
						<text class="cuIcon cuIcon-creative text-xxl "></text>
					</view>
					<view class="margin-top">
						<text>点击右上角分享给好友</text>
					</view>
				</view>
			</view>
		</view>
		<view class="cu-modal bottom-modal" :class="modalName=='typeModal'?'show':''">
			<view class="cu-dialog">
				<view class="bg-white cu-list col-2 grid no-border">
					<view class="cu-item" @click="createPoster">
						<view class="cuIcon cuIcon-album text-orange"></view>
						<view>海报</view>
					</view>
					<!-- <view class="cu-item">
						<view class="cuIcon cuIcon-form text-blue"></view>
						<view>文案</view>
					</view> -->
					<view class="cu-item" @click="wechatShare">
						<view class="cuIcon cuIcon-weixin text-green"></view>
						<view>微信</view>
					</view>
				</view>
				<view class="bg-white margin-top text-red padding-tb" @tap="modalName=''">
					取消
				</view>
			</view>
		</view>

	</view>
</template>

<script>
	// #ifdef H5
	import html2canvas from '../../common/unit/html2canvas.min.js'
	// #endif
	import QR from '@/common/unit/wxqrcode.js'
	export default {
		name: "shareview",
		// #ifdef H5
		components: {
			html2canvas
		},
		// #endif
		props: {
			// value: {
			// 	type: Object,
			// 	default: null
			// }
		},
		created: function(e) {},
		data() {
			return {
				modalName: '',
				id: 0,
				detail: null,
				member: null,
				qr_code: null,
				mainWidth: 0,
				mainHeight: 100,
				loading: true,
				value: {},
				previewFile: '',
				CLOUDPATH: this.$config.cloudPath
			}
		},
		methods: {
			showModal(value, member) {
				this.value = value
				console.log(value)
				this.member = member
				// this.modalName = 'typeModal'
				this.loading = true
				this.createPoster()
			},
			wechatShare() {
				this.modalName = 'wechatModal'
			},
			// #ifdef H5
			canvasToImage_H5() {
				html2canvas(document.querySelector('#_poster'), {
					allowTaint: false,
					useCORS: true,
					// height: data.height,
					// width: data.width
				}).then(canvas => {
					// document.body.appendChild(canvas)
					let previewFile = canvas.toDataURL('image/png')
					this.previewFile = previewFile
					this.loading = false
					uni.hideLoading()
				}).catch((e) => {
					console.log(e)
				});
			},
			// #endif
			downloadImage() {
				// #ifdef MP-WEIXIN
				// uni.saveImageToPhotosAlbum({
				// 	filePath: this.previewFile,
				// 	success: function() {
				// 		console.log('save success')
				// 		uni.showSuccess('保存成功，可在相册中查看')
				// 	}
				// })
				// #endif
			},
			canvasToImage(w, h) {
				let _this = this
				let info = uni.createSelectorQuery().in(this).select(".goodsimage")
				info.boundingClientRect((data) => { //data - 各种参数
					let imgw = data.width
					let imgh = data.height

					var context = uni.createCanvasContext('mycanvas', this)
					context.width = w
					context.height = h
					context.setFillStyle("#FFFFFF")
					context.fillRect(0, 0, w, h)
					this.getNetworkImage(this.member.head_portrait2).then((res) => {
						context.drawImage(res, 10, 10, 40, 40)
						this.drawText(context, {
							x: 60,
							y: 25,
							size: 14,
							align: 'left',
							text: this.member.nickname,
							color: "#333333",
							bold: false
						})
						this.drawText(context, {
							x: 60,
							y: 45,
							size: 12,
							align: 'left',
							text: '分享给你一个商品',
							color: "#999999",
							bold: false
						})
						this.drawText(context, {
							x: 20,
							y: imgh + 90,
							size: 20,
							align: 'left',
							text: '￥' + this.value.price,
							color: "#FF0000",
							bold: false
						})
						this.textWrap(context, {
							x: 20,
							y: imgh + 110,
							width: w - 80 - 60,
							height: 20,
							line: 2,
							size: 14,
							align: 'left',
							text: this.value.name,
							color: "#333333",
							bold: false
						})

						this.getNetworkImage(this.value.picture2).then((res2) => {
							context.drawImage(res2, 10, 60, imgw, imgh)
							this.base64src(this.qr_code).then((r) => {
								context.drawImage(r, w - 70 - 20, imgh + 70, 70, 70)
								context.save()
								context.draw(false, () => {
									uni.canvasToTempFilePath({
										x: 0,
										y: 0,
										width: w,
										height: h,
										destWidth: w,
										destHeight: h,
										canvasId: 'mycanvas',
										success: function(res) {
											// 在H5平台下，tempFilePath 为 base64
											console.log(res.tempFilePath)
											_this.previewFile = res.tempFilePath
											console.log(_this.previewFile)
											_this.loading = false
											uni.hideLoading()
										},
										fail(r) {
											console.log(r)
										}
									}, this)
								})
							})
						})
					})
				}).exec();
			},
			createPoster() {
				this.modalName = 'posterModal'
				uni.showLoading({
					title: '海报生成中...'
				})
				let share_url = this.value.share_url
				this.qr_code = QR.createQrCodeImg(share_url, {
					errorCorrectLevel: 'L',
					size: parseInt(300) //二维码大小  
				})
				setTimeout((res) => {
					let info = uni.createSelectorQuery().in(this).select("#_poster")
					info.boundingClientRect((data) => { //data - 各种参数
						this.mainHeight = data.height
						this.mainWidth = data.width

						// this.$nextTick((res) => {
						// #ifdef H5
						this.canvasToImage_H5()
						// #endif

						// #ifdef MP-WEIXIN
						this.canvasToImage(this.mainWidth, this.mainHeight)
						// #endif
						// })
					}).exec()
				}, 1000)
			},
			getNetworkImage(url) {
				return new Promise((resolve, reject) => {
					uni.downloadFile({
						url,
						success: (e) => {
							const p = e.tempFilePath
							if (p.indexOf('json') > -1) {
								reject(p)
								return false
							}
							resolve(p)
						},
						fail: (r) => {
							reject(r)
						}
					})
				})
			},
			base64src: function(base64data) {
				const fsm = wx.getFileSystemManager();
				const FILE_BASE_NAME = 'tmp_base64src';
				return new Promise((resolve, reject) => {
					const [, format, bodyData] = /data:image\/(\w+);base64,(.*)/.exec(base64data) || [];
					if (!format) {
						reject(new Error('ERROR_BASE64SRC_PARSE'));
					}
					const filePath = `${wx.env.USER_DATA_PATH}/${FILE_BASE_NAME}.${format}`;
					const buffer = wx.base64ToArrayBuffer(bodyData);
					fsm.writeFile({
						filePath,
						data: buffer,
						encoding: 'binary',
						success() {
							resolve(filePath);
						},
						fail() {
							reject(new Error('ERROR_BASE64SRC_WRITE'));
						},
					});
				});
			},
			drawText: function(ctx, obj) {
				ctx.save();
				ctx.setFillStyle(obj.color);
				ctx.setFontSize(obj.size);
				ctx.setTextAlign(obj.align);
				ctx.setTextBaseline(obj.baseline);
				if (obj.bold) {
					ctx.fillText(obj.text, obj.x, obj.y - 0.5);
					ctx.fillText(obj.text, obj.x - 0.5, obj.y);
				}
				ctx.fillText(obj.text, obj.x, obj.y);
				if (obj.bold) {
					ctx.fillText(obj.text, obj.x, obj.y + 0.5);
					ctx.fillText(obj.text, obj.x + 0.5, obj.y);
				}
				ctx.restore();
			},
			textWrap: function(ctx, obj) {
				var td = Math.ceil(obj.width / (obj.size));
				var tr = Math.ceil(obj.text.length / td);
				for (var i = 0; i < tr; i++) {
					var txt = {
						x: obj.x,
						y: obj.y + (i * obj.height),
						color: obj.color,
						size: obj.size,
						align: obj.align,
						baseline: obj.baseline,
						text: obj.text.substring(i * td, (i + 1) * td),
						bold: obj.bold
					};
					if (i < obj.line) {
						if (i == obj.line - 1) {
							txt.text = txt.text.substring(0, txt.text.length - 3) + '......';
						}
						this.drawText(ctx, txt);
					}
				}
			},
		},
	}
</script>

<style>
	.main {
		overflow: hidden;
		border-radius: 0 0 20rpx 20rpx;
	}

	.member {}

	.member .thumb {
		width: 100rpx;
		height: 100rpx;
		min-width: 100rpx;
	}

	.member .thumb image {
		width: 100%;
		height: 100%;
	}

	.line-orange {
		border: 1px solid #ffa530;
		border-radius: 8rpx;
	}

	.goodsimage {}

	.goodsimage image {
		width: 100%;
	}

	.goodsname {
		background-color: #F2F2F2;
		padding: 10rpx;
	}

	.goodsprice {
		font-size: 40rpx;
	}

	.qrcode {
		width: 220rpx;
		height: 220rpx;
	}

	.tips {
		width: 100%;
		margin-right: 60rpx;
	}

	.logo {
		padding: 10rpx;
	}

	.main-img {
		width: 100%;
	}

	.cu-dialog {
		border-radius: 0;
		background: none;
	}

	.w80 {
		width: 80%;
	}

	.cu-btn.lg {
		background: none;
		font-size: 60upx;
	}

	.member {}

	.member .thumb {
		width: 100rpx;
		height: 100rpx;
		min-width: 100rpx;
	}

	.member .thumb image {
		width: 100%;
		height: 100%;
	}

	.line-orange {
		border: 1px solid #ffa530;
		border-radius: 8rpx;
	}

	.goodsimage {}

	.goodsimage image {
		width: 100%;
	}

	.goodsname {
		background-color: #F2F2F2;
		padding: 10rpx;
	}

	.goodsprice {
		font-size: 40rpx;
	}

	.tips {
		width: 100%;
		margin-right: 60rpx;
	}

	.sharejiao {
		width: 100rpx;
		height: 100rpx;
	}

	.flex-end {
		display: flex;
		justify-content: flex-end;
		align-items: flex-end;
	}

	.canvas {
		position: absolute;
		left: 1000px;
	}
</style>
